package com.chenwut.myreflect.a03_reflect_feild;

import java.lang.reflect.Field;

/**
 * @author ChenPi
 * @since 2024/09/23 16:30
 */
public class MyReflectDemo {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
        /**
         * Class类中用于获取成员变量的方法
         * Field[] getFields()                                       返回所有公共成员变量对象的数组
         * Field[] getDeclaredFields()                               返回所有成员变量对象的数组
         * Field getField(String name)                               返回单个公共成员变量对象
         * Field getDeclaredField(String name)                       返回单个成员变量对象
         *
         * Field类中用于创建对象的方法
         * void set(Object obj,Object value)                         赋值
         * Object get(Object obj)                                    获取值
         */

        Class clazz = Class.forName("com.chenwut.myreflect.a03_reflect_feild.Student");

        // Field[] fields = clazz.getDeclaredFields();
        // for (Field field : fields) {
        //     System.out.println(field);
        // }

        Field field = clazz.getDeclaredField("name");
        System.out.println(field);

        int modifiers = field.getModifiers();
        System.out.println(modifiers);

        String fieldName = field.getName();
        System.out.println(fieldName);

        System.out.println(field.getType());


        // 获取成员变量记录的值
        Student student = new Student("张三", 18, "北京");
        field.setAccessible(true);
        Object value = field.get(student);
        System.out.println(value);

        // 修改成员变量的值
        field.set(student, "李四");
        System.out.println(student);
    }
}
